package 尊享面试.数组_字符串;

public class a161相隔为1的编辑距离 {
    static class Solution {
        public boolean isOneEditDistance0(String s, String t) {
            int dif = 0;
            int i = 0;
            int slen = s.length();
            int tlen = t.length();
            if (slen == tlen) {
                while (i < slen) {
                    if (s.charAt(i) != t.charAt(i)) {
                        if (++dif > 1) return false;
                    }
                    i++;
                }
                return dif != 0;
            }
            if (slen == tlen - 1) {
                while (i < slen) {
                    if (s.charAt(i) != t.charAt(i + dif)) {
                        if (++dif > 1) return false;
                    } else {
                        i++;
                    }
                }
                return true;
            }
            if (slen == tlen + 1) {
                while (i < tlen) {
                    if (t.charAt(i) != s.charAt(i + dif)) {
                        if (++dif > 1) return false;
                    } else {
                        i++;
                    }
                }
                return true;
            }
            return false;
        }

        public boolean isOneEditDistance(String s, String t) {
            int slen = s.length();
            int tlen = t.length();
            if (slen > tlen) { // 确保左边的长度短
                return isOneEditDistance(t, s);
            }
            if (tlen - slen > 1) return false;
            for (int i = 0; i < slen; i++) {
                if (s.charAt(i) != t.charAt(i)) {
                    if (slen == tlen) {
                        return s.substring(i + 1).equals(t.substring(i + 1));
                    } else {
                        return s.substring(i).equals(t.substring(i + 1));
                    }
                }
            }
            return slen == tlen - 1;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        String s = "ab", t = "acd";
        System.out.println(solution.isOneEditDistance(s, t));
    }
}
